<?php


namespace app\admin\controller;


use app\admin\common\Export;
use app\admin\common\library\FlowEngine;
use app\admin\common\Week;
use app\admin\common\WorkTime;
use app\admin\model\Alternative;
use app\admin\model\Approval;
use app\admin\model\FlowNumber;
use app\admin\model\FlowScheme;
use app\admin\model\FlowTask;
use app\admin\model\Overtime;
use app\admin\model\Scheme;
use app\BaseController;
use fast\Date;
use fast\Tree;
use think\facade\Db;
use think\facade\View;
use think\Request;

class Vacation extends BaseController
{

    protected $flow = null;
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];
    protected $scheme = null;
    protected $juese = null;
    protected $sum_jbd = null;

    public function initialize()
    {
        parent::initialize();
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()
                ->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist      = Tree::instance()->getTreeList(Tree::instance()
                    ->getTreeArray($n['id']));
                $temp           = [];
                $temp[$n['id']] = $n['name'];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result      = $temp;
                $this->juese = $n['name'];
            }
            $groupdata = $result;
        }
        $this->scheme  = new Scheme();
        $this->sum_jbd =
            \app\admin\model\Overtime::where(['user_id'  => $this->auth->id,
                                              'is_leave' => 0,
                                              'status'   => 2])
                ->sum('duration');
        View::assign('sum_jbd', $this->sum_jbd);
    }

    //添加事件
    public function addAlternative(Request $request)
    {
        if ($request->isAjax()) {
            $type = $request->param('status');
            if ($type == 0) {  //添加到备忘事件
                Alternative::create($request->param());
            } else { //直接写进日历
                $data                      =
                    $request->only(['color', 'remark', 'status']);
                $period                    =
                    explode('~', $request->param('time'));
                $data['start_time']        =
                    $period[0] ?? date('Y-m-d H:i:s', time());
                $data['end_time']          =
                    $period[1] ?? date('Y-m-d H:i:s', time());
                $data['alternative_title'] = $request->param('title');
                $data['admin_id']          = $this->auth->id;
                $data['username']          = $this->auth->nickname;
                foreach ($this->auth->getGroups() as $key => $value) {
                    $data['group_id']   = $value['id'];
                    $data['group_name'] = $value['name'];
                }
                if ($data) {
                    \app\admin\model\Vacation::create($data);
                }
            }
            return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
        }
    }

    //填写假条
    public function addVacation(Request $request)
    {

        $start = $request->param('start_time') . ' ' . '08:30';
        $end   = $request->param('end_time');
        if (array_key_exists('id', $request->param())) {
            $end = date('Y-m-d', strtotime($end)) . ' ' . '17:30';
        } else {
            $end = date('Y-m-d', strtotime("$end -1 day")) . ' ' . '17:30';
        }
        $id               = $request->param('id');
        $title            = $request->param('title');
        $alternatives     = Alternative::select()->toArray();
        $background_color = $request->param('background_color');
        $admin_id         = $this->auth->id;
        $username         = $this->auth->nickname;
        $group_arr        = $this->auth->getGroups();
        $group_id         = "";
        $group_name       = "";
        foreach ($group_arr as $key => $value) {
            $group_id   = $value['id'];
            $group_name = $value['name'];
        }
        $flow = \app\admin\model\Scheme::where('flowname', '请假')->select();
        if ($request->isAjax()) {
            $data       = $request->only(['username',
                'group_name',
                'alternative_title',
                'color',
                'start_time',
                'end_time',
                'remark',
                'alternative_id',
                'flow_id',
                'day']);
             
            $start_time = $request->param('start_time');
            $end_time   = $request->param('end_time');
//            $dy_start_time = $request->param('dy_start_time');
//            $dy_end_time = $request->param('dy_end_time');
            if ($data['alternative_title'] == "调休") {
//                $aa += $request->param('days') / 24;
                $hours = $request->param('days');// 接收当前调休的小时数
                $overtime_ids          = $request->param('corresponding');
                $data['corresponding'] = $overtime_ids;
                $data['day'] = $hours;
                //选择的加班时长总数
                $rre = Overtime::whereIn('id',$overtime_ids)->sum('duration');
                if($rre < $hours){
                    return json(['code' =>400, 'url' => '', 'msg' => '加班时长小于调休数']);
                }
                //把小时转换成天
//                $hours_to_day = $hours / 24;
                $hours_to_day = $hours / 7.5; //每天按8个小时计算
                $days = round($hours_to_day, 3) ?? 0;
                //改变当前加班单的状态
                Overtime::where('id', 'in',$overtime_ids)->update(['is_leave' => 1]);
            }else{
       
                $data['start_time'] = $start_time ?? date('Y-m-d H:i:s', time());
                $data['end_time']   = $end_time ?? date('Y-m-d H:i:s', time());
                #121、
                #--【  78945 8045 7845 790678905  7890 0-78 67890 6789= 9            $data['group_id'] = $group_id;
                $data['status'] = 1;
                $startdate      = strtotime($data['start_time']);
                $enddate        = strtotime($data['end_time']);
                $days           = round(($enddate - $startdate) / 3600 / 24);
            }
            $data['admin_id']   = $admin_id;
            if ($data) {
                $vacation = \app\admin\model\Vacation::create($data);
                if ($vacation) {
                    $scheme     = Scheme::find($data['flow_id']);
                    $serial_no  = $this->getnumber($scheme['flowcode']);
                    $this->flow = new FlowEngine($scheme['flowcode']);
                    $config     = [
                        'instancecode' => $serial_no,
                        'start_time'   => $data['start_time'],
                        'end_time'     => $data['end_time'],
                        'content'      => $data['remark'],
                        'day'          => $days,
                        'from_id'      => $vacation->id,
                        'from_table'   => 'vacations',

                    ];
                    $this->flow->start($config);
                }
                return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
            }
        }
        if (!empty($background_color)) {
            $color = RGBToHex($background_color); //rgb 颜色转换
        } else {
            $color = '#1c97f5'; //rgb 颜色转换
        }
        View::assign('alternatives', $alternatives);

        View::assign('id', $id);
        View::assign('title', $title);
        View::assign('start', $start);
        View::assign('end', $end);
        View::assign('username', $username);
        View::assign('background_color', $color);
        View::assign('group_name', $group_name);
        View::assign('flow', $flow);
        return View::fetch('administration/vacation/add_vacation');
    }



    //处理加班时长方法
    public function jbsc($overtime_ids)
    {
        //改变当前 状态   1为正在使用中 2,为使用完成
        return \app\admin\model\Overtime::where('id', 'in', $overtime_ids)->update([
            'is_leave' => 1, //正在使用中
        ]);
    }
////        $zongsc                =
////            \app\admin\model\Overtime::where('id', 'in', $overtime_ids)
////                ->sum('duration'); //总时长
////        $tiaoxiusc             = $day; //调休时长
////        if ($zongsc > $tiaoxiusc) { //删除后新增
////
////            //当前ids $overtime_ids
////            $res     = \app\admin\model\Overtime::where('id', 'in',
////                $overtime_ids)->find();
////            $now     = date("Y-m-d H:i", time()); //当前时间
////            $scc     = $zongsc - $tiaoxiusc; //时长差
////            $scc_arr = explode('.', $scc); //转成数组
////            if (count($scc_arr) > 1) { //如果时长存在半个小时，直接在当前时间段相加
////                $end_time = date("Y-m-d H:i",
////                    strtotime($now . "+" . $scc_arr[0] .
////                        " hours")); //加整数时长
////                $end_time = date("Y-m-d H:i", strtotime($end_time .
////                    "+30 minutes")); //加已半个小时为单位的时长
////            } else {
////                $end_time = date("Y-m-d H:i",
////                    strtotime($now . "+" . $scc_arr[0] . " hours"));
////            }
////            $info = [
////                'user_id'    => $res->user_id,
////                'user_name'  => $res->user_name,
////                'group_id'   => $res->group_id,
////                'group_name' => $res->group_name,
////                'start_time' => $now,
////                'end_time'   => $end_time,
////                'content'    => '来自' . $res->user_name .
////                    '调休剩余时长,来源于加班编号' . $overtime_ids,
////                'status'     => 2,
////                "flow_id"    => 10,
////                'ly_id'      => $overtime_ids,
////                "is_leave"   => 0,
////                "duration"   => $scc,
////            ];
////            //更新当前使用过后的加班时间段 暂不删除,直接更新当前状态，方便查看
////            $overtime = new \app\admin\model\Overtime;
////            $syhsc    =
////                $overtime->where('id', 'in', $overtime_ids)->select()
////                    ->each(function ($item, $key) {
////                        $item['is_leave'] = 2; //更改当前状态
////                    })->toArray();
////            $overtime->saveAll($syhsc);
////            //新增剩余时长记录入库
////           $create =  \app\admin\model\Overtime::create($info);
////           return $create;
////        } else {
////            if ($zongsc == $tiaoxiusc) { //直接更改已使用的状态
////               return \app\admin\model\Overtime::where('id', 'in',
////                    $overtime_ids)->update([
////                    'is_leave' => 2,
////                ]);
////            } else {
////                if ($tiaoxiusc > $this->sum_jbd) {
////                    return 400;
////                }
////            }
////        }
//    }

    //查看事件
    public function VacationDetail(Request $request, $id)
    {
        if ($id) {
            $model = \app\admin\model\Vacation::checkDetail($id);
            View::assign('model', $model);
            return View::fetch('administration/vacation/vacation_detail');
        } else {
            return "<span>信息不完善,请刷新页面后重新填写</span>";
        }
    }

    //拖拽事件
    public function eventDrop(Request $request)
    {
        if ($request->isAjax()) {
            $id         = $request->param('id');
            $start_time = $request->param('start_time');
            $end_time   = $request->param('end_time');
            $data       = [
                'id'         => $id,
                'start_time' => $start_time,
                'end_time'   => $end_time,
            ];
            if ($data) {
                \app\admin\model\Vacation::update($data);
                return json(['code' => 200, 'url' => '', 'msg' => '变更成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '变更失败！']);
        }
    }

    //删除时间
    public function del($id = "")
    {
        try {
            if ($id) {
                $ids = explode(',', $id);
                \app\admin\model\Vacation::destroy(array_values($ids));
                FlowTask::where(['from_table' => 'vacations', 'from_id' => $id])
                    ->delete(); //删除对应的工作流
            }
        } catch (\Exception $e) {
            return json(['code' => 400,
                         'url'  => '',
                         'msg'  => $e->getMessage()]);
        }
        return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
    }

    /**
     * [del_type description] 删除类别
     *
     * @param Request $request [description]
     *
     * @return [type]           [description]
     */
    public function del_type(Request $request)
    {
        $id = $request->param('id');
        try {
            if ($id) {
                $ids = explode(',', $id);
                Alternative::destroy(array_values($ids));
            }
        } catch (\Exception $e) {
            return json(['code' => 400,
                         'url'  => '',
                         'msg'  => $e->getMessage()]);
        }
        return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
    }

    /**
     * [update description]更新事件
     *
     * @param Request $request [description]
     * @param  [type]  $id      [description]
     *
     * @return [type]           [description]
     */
    public function update(Request $request, $id)
    {
        if ($request->isAjax()) {
            $data       = $request->only(['color',
                'remark',
                'start_time',
                'end_time',
                'flow_id',
                'day',
                'corresponding']);
            $data['id'] = $id;
            //查看是否改变了当前加班时间
            $data['corresponding'] = $request->param('corresponding');

            $ib = \app\admin\model\Vacation::find($data['id']);
            //1.当两者不相等的时候
            if ($data['corresponding'] !== $ib->corresponding) {
                //2.再次判断当选择的id 是否存在相关的id ly_id
                //备注：现在只是判断单一的，如果是个字符串的时候  该如何处理？
                $overtime = \app\admin\model\Overtime::find($data['corresponding']);
                if($overtime->ly_id === $ib->corresponding){
                    return json(['code' => 400, 'url' => '', 'msg' => '无法使用当前关联主加班记录！']);
                }else{
                    //处理编辑事务，改变加班记录，归还以及使用的记录
//                    //1.更新主记录表状态
                    $zhu = \app\admin\model\Overtime::find($ib->corresponding);
                    $zhu->is_leave     = 0;
                    $zhu->save();
//                    //2.删除副记录
                    \app\admin\model\Overtime::destroy(function($query) use ($ib){
                        $query->where('ly_id','=',$ib->corresponding);
                    });
//                    \app\admin\model\Overtime::where('ly_id',$ib->corresponding)->delete();
                    //调用加班时长的方法
                   $test = $this->jbsc($data['corresponding'],$data['day']);
                   if($test === 400){
                       return json(['code' => 400, 'url' => '', 'msg' => '更新失败！']);
                   }else{
                       if ($data) {
                           \app\admin\model\Vacation::update($data);
                           return json(['code' => 200, 'url' => '', 'msg' => '更新成功！']);
                       }
                       return json(['code' => 400, 'url' => '', 'msg' => '更新失败！']);
                   }
                }
            }
        }
    }

    public function backupdate(Request $request, $id)
    {
        if ($request->isAjax()) {
            $data                  = $request->only(['color',
                'remark',
                'start_time',
                'end_time',
                'flow_id',
                'corresponding']);
            $data['id']            = $id;
            $data['corresponding'] = $request->param('corresponding');
            $data['status']        = 1;
            if ($data) {
                $task       = FlowTask::where([
                    'receiveid'  => $this->auth->id,
                    'from_id'    => $id,
                    'from_table' => 'vacations',
                    'status'     => '0',
                ])->find(); //找到当前任务流程
                $res        = Db::name('view_workitem')->where([
                    'receiveid'  => $this->auth->id,
                    'from_id'    => $id,
                    'from_table' => 'vacations',
                    'status'     => '0',
                ])->find(); //找到当前任务视图
                $schme      = $this->scheme->find($task['flowid']);
                $this->flow = new FlowEngine($schme['flowcode']);
                $row        =
                    Db::name($res['bizscheme'])->find($res['bizobjectid']);
                $this->flow->next($res['id'], $row, '[拒绝后提交]');
                \app\admin\model\Vacation::update($data);
                return json(['code' => 200, 'url' => '', 'msg' => '更新成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '更新失败！']);
        }
    }


    //提示
    public function tips($id = "")
    {
        if ($id) {
            $res = Alternative::find($id);
            $msg = $res['remark'] ?? '暂无';
            return json(['code' => 200, 'url' => '', 'msg' => $msg]);
        }
    }


    //转换表格形式查看
    public function checkTable(Request $request)
    {
        $alternative = Alternative::select();
        $admin       = \app\admin\model\Admin::select();
        $va_group    = \app\admin\model\Vacation::field('group_id,group_name')
            ->distinct(true)->select();
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');

            $where = [];
            if ($request->has('alternative_id') &&
                !empty($request->get('alternative_id'))
            ) {
                $where[] =
                    ["alternative_id", "=", $request->get('alternative_id')];
            }
            if ($request->has('admin_id') &&
                !empty($request->get('admin_id'))
            ) {
                $where[] = ["admin_id", "=", $request->get('admin_id')];
            }
            if ($request->has('group_id') &&
                !empty($request->get('group_id'))
            ) {
                $where[] = ["group_id", "=", $request->get('group_id')];
            }
            if ($request->has('start_time') &&
                !empty($request->get('start_time'))
            ) {
                $where[] = ["start_time", ">=", $request->get('start_time')];
            }
            if ($request->has('end_time') &&
                !empty($request->get('end_time'))
            ) {
                $where[] = ["end_time", "<=", $request->get('end_time')];
            }

            if ($this->juese != "综合运营部") {
                $where[] = ['admin_id', 'in', $this->childrenAdminIds];
            }
            $res = \app\admin\model\Vacation::where($where)
                ->order('id', 'desc')
                ->paginate($limit, false, ['page' => $page])->toArray();
            return json(['code'  => 200,
                         'msg'   => '',
                         'total' => $res['total'],
                         'data'  => $res['data']]);
        }
        View::assign('admin', $admin);
        View::assign('va_group', $va_group);
        View::assign('alternative', $alternative);
        return View::fetch('administration/vacation/check_table');
    }

    //请假导出
    public function download(Request $request)
    {
        if ($request->isAjax()) {
            $where = [];
            if (!empty($request->post('ids'))) {
                $where[] = ["id", "in", $request->post('ids')];
            }
            $xlsName = "休假表" . time();
            $xlsCell = [
                ['alternative_title', '类型'],
                ['username', '用户名'],
                ['group_name', '部门'],
                ['start_time', '开始时间'],
                ['end_time', '结束时间'],
                ['remark', '描述'],
            ];
            $result  = \app\admin\model\Vacation::where($where)
                ->field('alternative_title,username,group_name,start_time,end_time,remark')
                ->select();
            $export  = new Export();
            $url     = $export->exportExcel($xlsName, $xlsCell, $result);
            echo json_encode($url);
            exit();
        }
    }

}
